<?php
/**
 * Created by XM·Tan.
 * Motto: Who shuts love out, in turn shall be shut out from love.
 * Date: 2021/3/22 22:21
 */

namespace app\admin\business;


use app\common\business\BusBase;
use app\common\lib\ArrayLib;
use app\common\lib\Password;
use app\common\model\mysql\Admin as AdminModel;
use think\Exception;
use think\facade\Log;

class AdminUser extends BusBase {

    public $model = null;

    public function __construct() {
        $this->model = new AdminModel();
    }

    /**
     * 获取管理员列表数据
     * @param $data
     * @param int $num
     * @return array
     */
    public function getLists($data, $num = 10) {

        $likeKeys = []; // 如果没有定义这个 有时候会报错
        if (!empty($data)) {
            $likeKeys = array_keys($data);
        }
        try {
            $list = $this->model->getLists($likeKeys, $data, $num);
            $result = $list->toArray();
        } catch (\Exception $e) {
            Log::error('common-business-AdminUser-getLists: ' . $e->getMessage());
            $result = ArrayLib::getPaginateDefaultData($num);
        }
        return $result;
    }

    /**
     * 新增管理员
     * @param $data
     * @return bool|mixed
     */
    public function insertData($data) {
        try {

            $admin = $this->model->getAdminByUsername($data['username']);
            if ($admin) {
                throw new Exception('管理员已存在');
            }

            $pass = Password::encrypt_password($data['password']);
            $data['password'] = $pass['password'];
            $data['encrypt'] = $pass['encrypt'];

            $id = $this->add($data);
            if (!$id) {
                return $id;
            }
            (new AdminGroup)->addAll($id, $data['role_id']);
            return true;
        } catch (\Exception $e) {
            Log::error('common-business-AdminUser-insertData: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 更新管理员
     * @param $data
     * @return bool|mixed
     */
    public function updateData($data) {
        $this->model->startTrans();
        try {
            if (!empty($data['password'])) {
                $pass = Password::encrypt_password($data['password']);
                $data['password'] = $pass['password'];
                $data['encrypt'] = $pass['encrypt'];
            } else {
                unset($data['password']);
            }
            unset($data['username']);
            $res = $this->edit($data['id'],$data);

            (new AdminGroup)->addAll($data['id'], $data['role_id']);
            // 提交事务
            $this->model->commit();
        } catch (\Exception $e) {
            Log::error('common-business-AdminUser-updateData: ' . $e->getMessage());
            // 回滚事务
            $this->model->rollback();
            return false;
        }
        return $res;
    }

    /**
     * 登录逻辑和数据操作
     * @param $data
     * @return bool
     * @throws Exception
     */
    public static function login($data) {
        try {
            $adminUser = self::getAdminByUsername($data['username']);
            if (empty($adminUser)) {
                throw new Exception('不存在该用户');
            }
            // 判断密码是否正确
            if ($adminUser['password'] != Password::encrypt_password($data['password'], $adminUser['encrypt'])) {
                throw new Exception('密码错误');
            }
            // 需要记录信息到 mysql 表中
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
                'update_time' => time()
            ];
            $res = (new AdminModel())->updateById($adminUser['id'], $updateData);
            if (empty($res)) {
                throw new Exception('登录失败');
            }

        } catch (\Exception $e) {
            // todo 记录日志 $e->getMessage();
            Log::error('admin-business-AdminUser-login: ' . $e->getMessage());
            throw new Exception($e->getMessage());
        }

        unset($adminUser['password']);
        unset($adminUser['encrypt']);
        // 记录 session
        session(config('admin.session_admin'), $adminUser);
        return true;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminByUsername($username) {
        $adminUser = (new AdminModel())->getAdminByUsername($username);
        if (empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')) {
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }

}